import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Button,Card,Form,Input,message} from 'antd';
import { ArrowLeftOutlined, } from '@ant-design/icons';
import { reqAddTeacher,reqUpdateTeacher } from '../../api'
import { saveTeacherAction } from '../../redux/action_creators/user_action';
import PicturesWall from '../../components/util/picture_wall';
import RichTextEditor from '../../components/util/rich_text_edit';
import './addUpdate.less';

const {Item} =Form;


@connect(
    (state)=>({
        teacherList:state.userList.teacherList
    }),
    {
        saveTeacherList:saveTeacherAction
    }
)
class AddUpdate extends Component {
    state={
        operateType:'add',
        username:'',
        userNum:'',
        degree:'',
        title:'',
        phone:'',
        email:'',
        img:[],
        detail:'',
        id:''
    }
    componentDidMount(){

        const { id } = this.props.match.params
        const { teacherList} = this.props
        if(id) {
            this.setState({operateType:'update'})
            if(teacherList.length){
               let result = teacherList.find((item)=>{
                   return item.id === parseInt(id)
               })
               if(result){
                   console.log(result);
                   this.setState({...result})
                   this.textEditor.setDetail(result.detail)
                   if(result.img){
                        this.pictureWall.setFileList(result.img.split(','))
                   }
               } 
            }else{
                const {img,detail} = this.props.location.state.teacherItem
                this.textEditor.setDetail(detail)
               if(img){
                        this.pictureWall.setFileList(img.split(','))
                   }
            }
        }else this.setState({operateType:'add'})
    }
    // 提交表单
    onFinish = async (values) => {
        // 从上传图片组件中获取图片地址数组
       let img = this.pictureWall.getImgArr()
       let detail = this.textEditor.getDetail()
       if(detail.length<9){
            message.error("请输入个人描述再提交！",1)
            return;
       }
       if(img.length<1){
            message.error("请上传课程图片再提交",1)
            return;
        }
       let result
       if(this.state.operateType === 'add'){
            result = await reqAddTeacher({...values,img,detail})
            const { code,data,msg } = result;
            if(code===200){
                message.success('添加成功！',1)
                let teacherList = [...this.props.teacherList]
                teacherList.unshift(data[0])
                this.props.saveTeacherList(teacherList)
                this.props.history.replace('/training/admin/teacher')
            }else{
                message.error(msg,2)
            }
        }else{
            const id= this.props.location.state.teacherItem.id
             result = await reqUpdateTeacher({...values,img,detail,id})
             const { code,data,msg } = result;
             console.log(data);
             if(code===200){
                 message.success('修改成功',1)
                 let teacherList = [...this.props.teacherList]
                 teacherList = teacherList.map((item)=>item.id === data.id ? data : item);
                 console.log(teacherList);
                 this.props.saveTeacherList(teacherList)
                 this.props.history.replace('/training/admin/teacher')
             }else{
                 message.success(msg,1)
             }
        }

    };
    // 表单填写有误
    onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
        // message.error('表单有误，请检查！',1)
    };
    render() {
        const { operateType } = this.state
        const {username,userNum,degree,title,phone,email,detail} = this.props.location.state.teacherItem
        return (
            
                <Card 
                    title={
                        <div className="left-top">
                            <Button 
                                type="link" 
                                size="small"
                                onClick={()=>{this.props.history.goBack()}} 
                            >
                                <ArrowLeftOutlined/>
                            </Button>
                            <span>{operateType==='update'?'讲师信息修改':'讲师信息添加'}</span>
                        </div>
                    }          
                >
                <Form
                    labelCol= {{span: 2,}}
                    wrapperCol= {{span: 6}}
                    name="basic"
                    initialValues={{
                        remember: true,
                        
                    }}
                    onFinish={this.onFinish}
                    onFinishFailed={this.onFinishFailed}
                >
                    <Item label="姓名"
                        name="username"
                        initialValue={username || ''}
                        rules={[{required: true,message: '姓名不能为空',}]}
                    >
                        <Input placeholder="姓名"  allowClear/>
                    </Item>
                    <Item label="工号"
                        name="userNum"
                        initialValue={userNum || ''}
                        rules={[{required: true,message: '工号不能为空',}]}
                    >
                        <Input placeholder="工号" allowClear disabled={operateType==="add"?false:true}/>
                    </Item>
                    <Item label="学位"
                        name="degree"
                        initialValue={degree || ''}
                        rules={[{required: true,message: '学位信息不能为空',}]}
                    >
                        <Input placeholder="学位" allowClear/>
                    </Item>
                    <Item label="职称"
                        name="title"
                        initialValue={title || ''}
                        rules={[{required: true,message: '职称不能为空',}]}
                    >
                        <Input placeholder="职称" allowClear/>
                    </Item>
                    <Item label="电话"
                        name="phone"
                        initialValue={phone || ''}
                        rules={[{required: true,message: '电话不能为空',}]}
                    >
                        <Input placeholder="电话" allowClear/>
                    </Item>
                    <Item label="邮箱"
                        name="email"
                        initialValue={email || ''}
                        rules={[{required: true,message: '邮箱不能为空',}]}
                    >
                        <Input placeholder="邮箱" allowClear/>
                    </Item>                 
                    <Item label="个人描述"
                            name="detail"
                            initialValue={detail || ''}
                            wrapperCol= {{span: 10}}
                        >
                        <RichTextEditor ref={(textEditor)=>{this.textEditor = textEditor}}/>
                    </Item>
                    <Item label="个人照片"
                        name="img"
                        wrapperCol= {{span: 12}}
                    >
                        <PicturesWall  ref={(pictureWall)=>{this.pictureWall = pictureWall}}/>
                    </Item>
                    {operateType==='add'?<div className="pic">注：初始密码为：12345678</div>:'' }                
                    <Item  wrapperCol={{ offset: 2, span: 24}} >
                        <Button  type="primary" htmlType="submit" className="login-from-button">提交</Button>
                    </Item>
                </Form>
                </Card>
            
        )
    }
}
export default  AddUpdate;